<template>
  <div id="product-form-page" v-if="form.id>-1">
    <div class="page-title" style="position: fixed; width: 100%; z-index: 999" :style="{
      top:(this.getSafeArea().top)+'px'
    }">
      <div id="back-button" @click="$router.push('/ProductList')">
        <i href="javascript:void(0)" class="el-icon-arrow-left"></i>
      </div>
      <span>商品-{{ info }}</span>
    </div>

    <el-form
      v-loading="currLoading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      style="position: relative;overflow-x: hidden; overflow-y: auto; padding-bottom: 60px" :style="{
      top:(43+this.getSafeArea().top+15)+'px',
      height: (this.getWinSize().height-43-this.getSafeArea().top-55)+'px',
    }" v-if="!currLoading" ref="form" :model="form" label-width="60px" :rules="rules">
      <el-form-item label="名称" align="left" prop="name">
        <el-input v-model.trim="form.name" style="width: 150px"></el-input>
      </el-form-item>
      <el-form-item label="热门标签" align="left" prop="hotTag">
        <el-input v-model.trim="form.hotTag" :maxlength="10" style="width: 150px"></el-input>
      </el-form-item>
      <el-form-item label="品牌" align="left">
        <shop-brand-box ref="shop-brand-box" :set-call-back="setBrand" :init-brand="form.brandId?form.brandId:0"/>
      </el-form-item>
      <el-form-item label="分类" align="left" prop="classifyName">
        <el-tag v-text="form.classifyId>0?form.classifyName:'-'" @click="chooseClassify"></el-tag>
      </el-form-item>
      <el-form-item label="主图" align="left" prop="image">
        <el-upload
          class="avatar-uploader"
          :action="UploadFileUrl"
          :headers="getHeader()"
          name="myUploadFile"
          :show-file-list="false"
          :on-success="uploadIconSuccess">
          <img v-if="form.image" :src="form.image" class="avatar" style="width: 100px; max-height: 100px;">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <el-input v-model="form.image" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item label="多图" align="left" prop="imageArr">
        <my-upload-more ref="my-upload-more" :image-params-arr="form.imageArr" :callback="callbackSetImageArr"/>
      </el-form-item>
      <el-form-item label="规格" align="left" prop="specifications">
        <product-specifications-select-box ref="product-specifications-select-box" :callback="setSpecifications"/>
      </el-form-item>
      <el-form-item label="型号" align="left"
                    v-if="!((!form.modelArr || form.modelArr.length===0) && $route.query.id>0)">
        <!--        <product-model-box ref="product-model-box" :init-curr-list="form.modelArr"/>-->
        <div>
          <div class="default-model-item" v-if="defaultModelItem.model">
            <div class="model ovd_s" :style="{
              maxWidth:(this.getWinSize().width-242)+'px'
            }" v-text="defaultModelItem.model"></div>
            <div class="nums" v-text="defaultModelItem.nums"></div>
            <div class="price red" v-text="'￥'+ToMoney(defaultModelItem.price)"></div>
            <div class="c"></div>
          </div>
          <div class="all-model-nums" v-text="form.modelArr.length+'条'"></div>
          <div class="c"></div>
        </div>
        <el-button type="success" @click="createModelItem">新增</el-button>
        <el-button type="primary" @click="managerModelItem" v-if="form.modelArr && form.modelArr.length>0">管理
        </el-button>
      </el-form-item>
      <el-form-item label="描述" align="left" prop="content">
        <my-editor ref="my-editor" :call-back="editorSetContent"/>
      </el-form-item>
    </el-form>
    <div align="center"
         style="position: fixed; width: 100%; bottom:0px; height: 40px; line-height: 40px; background: rgba(180,180,180,0.5);z-index:9999">
      <el-button type="success" size="small" style="width: 180px;" @click="submit">提 交</el-button>
    </div>
  </div>
</template>

<script>
import TableFieldTools from '../tools/TableFieldTools'
import ProductModelBox from '../common/ProductModelBox'
import ProductSpecificationsBox from '../common/ProductSpecificationsBox'
import MyEditor from '../common/MyEditor'
import MyUploadMore from '../common/MyUploadMore'
import ShopBrandBox from '../common/ShopBrandBox'
import ProductSpecificationsSelectBox from '../common/ProductSpecificationsSelectBox'

var demoModelList = [
  // {
  //   nums: 100,
  //   price: 35,
  //   image: 'http://image.yangfankj.com/shop/logo/2.jpg',
  //   model: '1111111111111111',
  //   weight: '',
  //   volume: '',
  //   status: true,
  //   isDefault: true,
  // },
  // {
  //   nums: 100,
  //   price: 30,
  //   image: 'http://image.yangfankj.com/shop/logo/3.jpg',
  //   model: '222222222222222',
  //   weight: '',
  //   volume: '',
  //   status: true,
  //   isDefault: false,
  // },
  // {
  //   nums: 100,
  //   price: 25,
  //   image: 'http://image.yangfankj.com/shop/logo/6.jpg',
  //   model: '333333333333333',
  //   weight: '',
  //   volume: '',
  //   status: true,
  //   isDefault: false,
  // }
]

export default {
  name: 'ProductForm',
  components: {
    ProductSpecificationsSelectBox,
    ShopBrandBox,
    MyUploadMore,
    MyEditor,
    ProductSpecificationsBox, ProductModelBox
  },
  props: {
    successFunction: Function
  },
  data: function () {
    let $this=this
    var checkHotTag=function (rule, value, callback) {
      if ($this.checkHotTag(value+'')) {
        callback()
      } else {
        callback(new Error('热门标签，由(中文/数字/字母)0,10位'))
      }
    }
    return {
      defaultClassifyName: [],
      classifyNameOptions: [],
      info: '',
      dialogVisible: true,
      currLoading: false,
      statusArr: dict.StatusArr,
      productClassifyNameArr: dict.ProductClassifyNameArr,
      shopProductAllClassifyArr: [],
      defaultModelItem: {
        model: '',
        price: 0,
        nums: 0,
      },
      form: {
        id: -1,
        name: '',
        hotTag: '',
        classifyId: [],
        classifyName: '',
        brandId: '',
        image: '',
        modelArr: [],
        defaultModel: '',
        imageArr: [],
        specificationsData: [],
        status: '1',
        content: ''
      },
      rules: {
        name: [
          {required: true, message: '请输入 名称', trigger: ['blur', 'change']},
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: ['blur', 'change']}
        ],
        hotTag:[
          {required: false, message: '', trigger: ['blur', 'change']},
          {validator:checkHotTag}
        ],
        brandId: [
          {required: false, message: '请选择 品牌', trigger: ['blur', 'change']}
        ],
        classifyName: [
          {required: true, message: '请选择 分类', trigger: ['blur', 'change']},
        ],
        image: [
          {required: true, message: '请上传 主图', trigger: ['blur', 'change']},
        ],
        imageArr: [
          {required: false, message: '请上传 多图', trigger: ['blur', 'change']},
        ],
        modelArr: []
      }
    }
  },
  mounted () {
    if (this.$route.query.id === 0 || !this.$route.query.id) {
      localStorage.removeItem('CurrProduct')
      this.open({})
    } else {
      this.getDetail()
    }
  },
  methods: {
    setSpecifications: function (specificationsData) {
      specificationsData.forEach(function (value, index) {
        if (typeof value.itemList === 'string') {
          specificationsData[index].itemList = value.itemList.split(',')
        }
      })
      this.form.specificationsArr = specificationsData ? specificationsData : []
    },
    getDetail: function (callback) {
      let $this = this
      $this.info = '更新'
      $this.currLoading = true
      $this.MyRequest($this.ApiDoNameShop + 'Product/getProductDetail', {id: this.$route.query.id}, function (data) {
        data.shopProduct.imageArr = JSON.parse(data.shopProduct.imageArr)
        $this.form = data.shopProduct
        var tmpArr = []
        data.shopProductStockList.forEach(function (value, index) {
          value.status = value.status.id === 1
          value.isDefault = value.isDefault.id === 1
        })
        console.log('data.shopProductStockList', data.shopProductStockList)
        $this.form.modelArr = data.shopProductStockList
        $this.form.specificationsArr = JSON.parse(data.shopProduct.specificationsArr)
        $this.getDefaultModel()
        $this.currLoading = false
        $this.$forceUpdate()
        if (typeof callback === 'function') {
          callback()
        }
        setTimeout(function () {
          $this.$refs['my-editor'].setContent($this.form.content)
          $this.$refs['my-upload-more'].setImageArr($this.form.imageArr)
          $this.$refs['product-specifications-select-box'].setSelectIds($this.form.specificationsArr)
        }, 500)
      }, function (response) {
        $this.$message.success(response.message)
        $this.currLoading = false
        $this.$forceUpdate()
      })
    },
    setBrand: function (brandId) {
      this.form.brandId = brandId
    },
    managerModelItem: function () {
      let $this = this
      $this.bus.$emit('ManagerModelDialogCallBus', $this.form.modelArr, $this.form.specificationsArr, function (modelArr) {
        console.log('modelArr',modelArr)
        $this.modelArr = modelArr
        $this.getDefaultModel()
        $this.$forceUpdate()
      })
    },
    getDefaultModel: function () {
      var defaultModel = {}
      let $this = this
      $this.form.modelArr.forEach(function (value, index) {
        if (value.isDefault) {
          defaultModel = value
        }
      })
      $this.defaultModelItem = defaultModel
      $this.$forceUpdate()
    },
    createModelItem: function (model) {
      let $this = this
      $this.bus.$emit('CreateModelDialogCallBus', model, $this.form.specificationsArr, function (model) {
        if (model.isDefault) {
          $this.form.modelArr.forEach(function (value, index) {
            $this.$set($this.form.modelArr[index], 'isDefault', false)
          })
        } else {
          if ($this.form.modelArr.length === 0) {
            model.isDefault = true
          }
        }
        $this.form.modelArr.push(model)
        $this.getDefaultModel()
      })
    },
    chooseClassify: function () {
      let $this = this
      this.bus.$emit('ChooseProductClassifyDialogCallBus', $this.form.classifyId, function (classifyItem) {
        $this.form.classifyId = classifyItem.id
        $this.form.classifyName = classifyItem.name
      })
    },
    // 打开弹窗
    open: function () {
      let $this = this

      $this.info = '创建'
      $this.form = {
        id: 0,
        name: '',
        hotTag: '',
        classifyName: '',
        brandId: '',
        classifyId: 0,
        modelArr: Object.assign([], demoModelList),
        defaultModel: '',
        image: '',
        imageArr: [],
        content: ''
      }
      $this.getDefaultModel()
      if ($this.$refs.form) {
        $this.$refs.form.resetFields()
      }
      $this.dialogVisible = true
      if (process.env.NODE_ENV === 'development') {
        // this.setDemo()
      }
      $this.$forceUpdate()
    },
    setDemo: function () {
      this.form.name = '测试产品'
      this.form.brandId = '测试品牌'
      this.form.price = 20
      this.form.image = 'http://image.yangfankj.com/product/110/0.jpg'
      let $this = this
      setTimeout(function () {
        $this.$refs['product-model-box'].setList([{'name': '功率', 'arr': ['大', '小']}, {
          'name': '颜色',
          'arr': ['黑', '白', '红']
        }], '大,白', 20)
        $this.$refs['my-editor'].setContent('<b>123456<b>')
        $this.$refs['product-specifications-box'].setList([{'name': '重量', 'value': '10kg'}, {
          'name': '体积',
          'value': '100cm*150cm*200cm'
        }])
        $this.uploadImageArr = TableFieldTools.formatImageArr(['http://image.yangfankj.com/product/110/0.jpg', 'http://image.yangfankj.com/product/110/1.jpg'])
        $this.form.classifyName = $this.getClassifyAllPathByName('浴巾')
        // console.log('$this.form.classifyName', $this.form.classifyName)
      }, 500)
    },
    editorSetContent: function (content) {
      this.form.content = content
    },
    uploadIconSuccess: function (res) {
      this.form.image = res.data
    },
    confirmClassityName: function (value) {
      console.log('this.form.classifyName', this.form.classifyName)
    },
    callbackSetImageArr: function (imageArr) {
      this.form.imageArr = imageArr
    },
    submit: function () {
      let $this = this
      $this.$refs.form.validate((valid) => {
        if (valid) {
          var api = 'Product/createProductAndModel'
          var form = Object.assign({}, $this.form)
          if (this.form.id > 0) {
            api = 'Product/updateProductAndModel'
          }
          if (form.classifyId===0){
            return $this.$message.success('商品分类 不能为空')
          }
          if ($this.form.imageArr.length > 0) {
            form.imageArr = $this.form.imageArr.join(',')
          } else {
            delete form.imageArr
          }
          if (form.modelArr.length === 0) {
            return $this.$message.success('型号列表 不能为空')
          }
          form.modelArr.forEach(function (value, index) {
            form.modelArr[index].status = value.status ? 1 : 0
            form.modelArr[index].isDefault = value.isDefault ? 1 : 0
            delete form.modelArr[index].numsStatus
            delete form.modelArr[index].shopSkillStatus
          })
          form.modelArr = JSON.stringify(form.modelArr)
          if (!form.specificationsArr || typeof form.specificationsArr==='undefined'){
            form.specificationsArr = '[]'
          }else{
            form.specificationsArr = JSON.stringify(form.specificationsArr)
          }
          if (!form.brandId) {
            delete form.brandId
          }
          if (!form.classifyId) {
            return $this.$message.error('产品分类 必须')
          }
          if (!form.content) {
            delete form.content
          }
          $this.currLoading = true
          $this.MyRequest(this.ApiDoNameShop + api, form, function () {
            $this.$message.success($this.info + '成功')
            $this.currLoading = false
            $this.$router.push('/ProductList')
            $this.$forceUpdate()
          }, function (response) {
            $this.$message.success(response.message)
            $this.currLoading = false
            $this.$forceUpdate()
          })
        } else {
          return false
        }
      })
    },
  }
}
</script>

<style scoped>
.default-model-item {
  display: inline-block;
  width: 82%;
  background: #f1f1f1;
  padding: 3px;
  margin-bottom: 5px;
  border: 1px solid #CCCCCC;
  border-radius: 3px;
  float: left
}

.all-model-nums {
  display: inline-block;
  width: 15%;
  float: left;
  text-align: center;
  line-height: 35px;
  color: #d24242;
  font-weight: bold
}

.default-model-item > .model {
  display: inline-block;
  width: 50%;
  float: left;
  text-align: center;
}

.default-model-item > .nums {
  display: inline-block;
  width: 25%;
  float: left;
  text-align: center;
  font-weight: bold
}

.default-model-item > .price {
  display: inline-block;
  width: 25%;
  float: left;
  text-align: center
}
</style>
